package controller;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class BaseServlet
 */
@WebServlet("/BaseServlet")
public class BaseServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		// 1 获取方法名字
		String methodName = req.getParameter("method");
		if(methodName == null){    //如果method参数为空
            throw new RuntimeException("请传递method参数以确定您要调用的方法！");
        }
		Method method = null;
		try {
			method = this.getClass().getMethod(methodName , HttpServletRequest.class , HttpServletResponse.class);
			
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		}
		try {
			method.invoke(this,req,resp);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
//		// 2获取当前对象字节码文件
//		Class servletClass = this.getClass();
//		// 3获取该字节码对象中的方法
//		try {
//			Method classMethod = servletClass.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
//			// 4執行方法
//			classMethod.invoke(this,req,resp);
//		} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
	}

}
